import { login, getUserInfo, logout } from "@/api/login";
import { setCache, getCache } from "@/utils/cacheUtils/cache";
import {
  setAccessToken,
  clearTokenCache,
} from "@/utils/cacheInstanceUtils/accessTokenCache";
// import { removeWebSite } from "@/utils/cacheInstanceUtils/webSiteCache";
import {
  setUserCache,
  clearUserCache,
  USER_CACHE_KEYS,
} from "@/utils/cacheInstanceUtils/userCache";

//  存放状态 类似vue data属性
const state = {
  id: getCache(USER_CACHE_KEYS.ID) || "",
  nickName: getCache(USER_CACHE_KEYS.NICKNAME) || "",
  age: getCache(USER_CACHE_KEYS.AGE) || "",
  gender: getCache(USER_CACHE_KEYS.GENDER) || "",
  phone: getCache(USER_CACHE_KEYS.PHONE) || "",
  avatar: getCache(USER_CACHE_KEYS.AVATAR) || "",
  userType: getCache(USER_CACHE_KEYS.USER_TYPE) || "",
  account: getCache(USER_CACHE_KEYS.ACCOUNT) || "",
  lastLoginIp: getCache(USER_CACHE_KEYS.LAST_LOGIN_IP) || "",
  lastLoginTime: getCache(USER_CACHE_KEYS.LAST_LOGIN_TIME) || "",
  isLoggedIn: getCache(USER_CACHE_KEYS.IS_LOGGED_IN) || false,
  alipayQrCode: getCache(USER_CACHE_KEYS.ALIPAY_QRCODE) || "",
  wxQrCode: getCache(USER_CACHE_KEYS.WX_QRCODE) || "",
};

// 操作state数据的方法的集合，比如对该数据的修改、增加、删除等等，参数一是当前VueX对象中的state，参数二是该方法在被调用时传递参数使用的
const mutations = {
  setUerInfo(state, payLoad) {
    const userInfo = {
      id: payLoad.id,
      lastLoginIp: payLoad.lastLoginIp,
      lastLoginTime: payLoad.lastLoginTime,
      nickName: payLoad.nickName,
      avatar: payLoad.avatar,
      userType: payLoad.userType,
      age: payLoad.age,
      gender: payLoad.gender,
      phone: payLoad.phone,
      account: payLoad.account,
      isLoggedIn: true,
      alipayQrCode: payLoad.alipayQrCode,
      wxQrCode: payLoad.wxQrCode,
    };
    Object.assign(state, userInfo);
    setUserCache(userInfo, {
      expires: 2 * 60 * 60 * 1000, // 1小时
    });
  },
  setQrCode(state, payLoad) {
    if (payLoad.type === "alipay") {
      state.alipayQrCode = payLoad.qrcode;
      setCache(USER_CACHE_KEYS.ALIPAY_QRCODE, state.alipayQrCode);
    } else {
      state.wxQrCode = payLoad.qrcode;
      setCache(USER_CACHE_KEYS.ALIPAY_QRCODE, state.alipayQrCode);
    }
  },
  resetUserState(state) {
    const defaultState = {
      id: "",
      nickName: "",
      age: "",
      gender: "",
      phone: "",
      avatar: "",
      userType: "",
      account: "",
      lastLoginIp: "",
      lastLoginTime: "",
      isLoggedIn: false,
      alipayQrCode: null,
      wxQrCode: null,
    };
    Object.assign(state, defaultState);
  },
};

const getters = {
  isLoggedIn: (state) => state.isLoggedIn,
  nickName: (state) => state.nickName,
  avatar: (state) => state.avatar || "/default-avatar.png",
  userType: (state) => state.userType,
  account: (state) => state.account,
  id: (state) => state.id,
  alipayQrCode: (state) => state.alipayQrCode,
  wxQrCode: (state) => state.wxQrCode,
};
// 异步操作
const actions = {
  /**
   * 登录，获取令牌
   * @param {} userInfo
   */
  async login({ commit }, userInfo) {
    try {
      const res = await login(userInfo);
      if (res.code == 200) {
        // 记录token
        setAccessToken(res.data);
        return res;
      } else {
        throw new Error(res.msg || "登录失败");
      }
    } catch (error) {
      throw error;
    }
  },

  /**
   * 调用getUserInfo方法以后，进入actions，
   * 然后通过commit调用setUserInfo，将res（用户信息）作为参数传入传入进去，并将相对应的属性值赋值给state，
   * @param { 可以理解为它是整个Store的对象.类似于this.$store， 他里面包含了state，getter，mutations，actions } context
   */
  async getUserInfo({ commit }) {
    try {
      const res = await getUserInfo();
      if (res.code == 200) {
        //相当于 this.$store.commit,第一个参数是方法名，第二个参数是要传入的数据
        commit("setUerInfo", res.data);
        return res;
      } else {
        throw new Error(res.msg || "获取用户信息失败");
      }
    } catch (error) {
      throw error;
    }
  },
  // 登出
  async logout({ commit, state }) {
    try {
      // 清除token缓存
      clearTokenCache();

      // 清除用户缓存
      const clearSuccess = clearUserCache();
      if (!clearSuccess) {
        console.warn("部分用户缓存清除失败");
      }

      // 重置用户状态
      commit("resetUserState");

      return true;
    } catch (error) {
      console.error("Logout failed:", error);
      return false;
    }
  },
};

export default {
  namespaced: true,
  state,
  getters,
  mutations,
  actions,
};
